package com.gaofans.nrpc.common.protocol;

import io.netty.buffer.ByteBuf;

/**
 * 一共64个字节的请求头
 * @author GaoFans
 */
public class ProtocolHeader {

    /**
     * 4个字节的魔数
     */
    private static final int MAGIC_NUM = 0x9050207;
    /**
     * 2个字节的请求版本
     */
    private final short version;
    /**
     * 1个字节的序列化类型
     */
    private final byte serializeType;
    /**
     * 1个字节的消息类型
     */
    private final byte messageType;
    /**
     * 8个字节的消息id
     */
    private final long sequenceId;
    /**
     * 编码器类型
     */
    private final byte codecType;
    /**
     * 暂时没用的42个空白字节
     */
    private final byte[] bytes = new byte[43];
    /**
     * 4个字节的正文长度
     */
    private final int length;

    public ProtocolHeader(short version,
                          byte serializeType,
                          byte messageType,
                          long sequenceId,
                          int length,
                          byte codecType) {
        this.version = version;
        this.serializeType = serializeType;
        this.messageType = messageType;
        this.sequenceId = sequenceId;
        this.length = length;
        this.codecType = codecType;

    }

    public int getMagicNum() {
        return MAGIC_NUM;
    }

    public short getVersion() {
        return version;
    }

    public byte getSerializeType() {
        return serializeType;
    }

    public byte getMessageType() {
        return messageType;
    }

    public long getSequenceId() {
        return sequenceId;
    }

    public byte[] getBytes() {
        return bytes;
    }

    public int getLength() {
        return length;
    }

    public byte getCodecType() {
        return codecType;
    }

    public void writeBuf(ByteBuf buf){
        buf.writeInt(getMagicNum());
        buf.writeShort(getVersion());
        buf.writeByte(getSerializeType());
        buf.writeByte(getMessageType());
        buf.writeLong(getSequenceId());
        buf.writeByte(getCodecType());
        buf.writeBytes(getBytes());
        buf.writeInt(getLength());
    }

    public ProtocolHeader(ByteBuf buf){
        int magicNum = buf.readInt();
        if (magicNum != MAGIC_NUM){
            throw new IllegalArgumentException("魔数异常");
        }
        this.version = buf.readShort();
        this.serializeType = buf.readByte();
        this.messageType = buf.readByte();
        this.sequenceId = buf.readLong();
        this.codecType = buf.readByte();
        buf.readBytes(this.bytes,0,this.bytes.length);
        this.length = buf.readInt();
    }
}
